import { loginapi, getInfoApi } from '@/api/user'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { getEmployeesApi } from '@/api/Employees.js'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
    setTimeStamp()
  },
  removeToken(state) {
    state.token = null,
      removeToken()
  },
  saveUserInfo(state, payload) {
    state.userInfo = payload
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  },
  async login(context, payload) {
    try {
      const res = await loginapi(payload)
      if (res.success) {
        const token = res.data
        context.commit('setToken', token)
      }
    } catch (error) {
      return Promise.reject(error)
    }
  },
  async getUserInfo(context) {
    const res = await getInfoApi()
    const baseRes = await getEmployeesApi(res.data.userId)
    const result = { ...res.data, ...baseRes.data }
    context.commit('saveUserInfo', result)
    return result
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

